package com.huafeng.config;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huafeng.context.ListenerContext;
import com.huafeng.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * @author 花风
 * @date 2022/11/30 21:40
 * @Description webSocket配置类
 */
@Slf4j
@Configuration
public class WebSocketConfig {
    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    public WebSocketClient webSocketClient(){
        try {
            WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://127.0.0.1:5701"), new Draft_6455()){

                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    log.info("[webSocket] 连接成功");
                }
                @Override
                public void onMessage(String message) {
                    try {
                        JsonNode tree = objectMapper.readTree(message);
                        String type = tree.get("post_type").asText();
                        Listener listener = ListenerContext.get(type);
                        listener.parse(message);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    log.info("[webSocket] 退出连接");
                }

                @Override
                public void onError(Exception e) {
                    log.error(e.getMessage());
                }
            };
            webSocketClient.connect();
            return webSocketClient;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
}
